package com.louis.iread.adapter;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.louis.iread.bean.Book;
import com.louis.iread.bean.BookMgr;
import com.louis.iread.skin.SkinMgr;

import java.util.Collections;
import java.util.List;


/**
 * Created by louis on 17-4-6.
 */

public class BookListAdapter extends BaseAdapter {
    private Context context;
    private LayoutInflater inflater;
    private int layoutId;
    private int variableId;
    private List<Book> mBooks;
    public BookListAdapter(Context context, int layoutId, int resId) {
        this.context = context;
        this.layoutId = layoutId;
        this.variableId = resId;
        inflater = LayoutInflater.from(context);
        mBooks = BookMgr.getMgr().getBooks();
        Collections.sort(mBooks);
    }

    public void updateBookList() {
        mBooks = BookMgr.getMgr().getBooks();
    }

    public void sortBooks() {
        Collections.sort(mBooks);
    }
    @Override
    public int getCount() {
        return mBooks.size();
    }

    @Override
    public Object getItem(int i) {
        return mBooks.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewDataBinding dataBinding = null;
        if (view == null) {
            dataBinding = DataBindingUtil.inflate(inflater, layoutId, viewGroup, false);
            view = dataBinding.getRoot();
            view.setTag(dataBinding);
        }else{
            dataBinding = (ViewDataBinding) view.getTag();
        }
        dataBinding.setVariable(variableId, BookMgr.getMgr().getBooks().get(i));
        SkinMgr.getInstance().applyView(view);
        return view;
    }
}
